///// this has been partially converted from a auto-restarting remoting app
///// into an auto-restarting urlloader app. It will not work, as is.

class FileClient {

	public static var client : FileClient;

	public var status : Int;
	
	public var updatecallback : String->Void;

	public var url : flash.net.URLRequest;

	public var loader : flash.net.URLLoader;
	
	public static inline var status_disconnected = 0;
	public static inline var status_transferring = 1;
	public static inline var status_success = 2;
	public static inline var status_waiting = 3;
	public static inline var status_connecting = 4;

	public static var retrytimer = new flash.utils.Timer(6000, 1);
		
	public function new(url : flash.net.URLRequest, 
						updatecallback : String->Void) 
	{
		client = this;
		inst = this;
		this.status = status_connecting;
		this.url = url;
		this.updatecallback = updatecallback;
		updatecallback(
			"Connecting to "+url.url);
		loader = new flash.net.URLLoader();
		configureListeners(loader);
		loader.addEventListener(flash.events.Event.OPEN, onConnect,
			false, 1, true);
		loader.addEventListener(flash.events.IOErrorEvent.IO_ERROR, ioerror,
			false, 1, true);
		loader.addEventListener(
						flash.events.SecurityErrorEvent.SECURITY_ERROR, 
							securityerror,
			false, 1, true);
		loader.addEventListener(
						flash.events.ProgressEvent.PROGRESS, 
							progress,
			false, 1, true);
		loader.addEventListener(
						flash.events.Event.COMPLETE, 
							complete,
			false, 1, true);
		loader.load(url);
		retrytimer.addEventListener(flash.events.TimerEvent.TIMER,
						   retry);		
		retrytimer.start();		
	}

	public function onConnect(e : flash.events.Event)
	{
		this.status = status_waiting;
		updatecallback("Connected");
		retrytimer.stop();
	}

	public function retry(?e : Dynamic)
	{
		updatecallback("Retrying...");

		loader.close();		
		client = new FileClient(this.domainname, this.portnum,
		this.updatecallback);		
	}

	public function setretry()
	{
		indata = new StringBuf();
		updatecallback("Trying to connect...");
		retrytimer.start();
	}

	public function close(e : flash.events.Event)
	{
		status = status_disconnected;
		updatecallback("Connection closed by foreign host");
		setretry();
	}

	public function ioerror(e : flash.events.IOErrorEvent)
	{
		status = status_disconnected;
		updatecallback("Connection closed by foreign host");
		setretry();
	}

	public function securityerror(e : flash.events.IOErrorEvent)
	{
		status = status_disconnected;
		updatecallback("Security error");
		setretry();
	}

	public function complete(e : flash.events.IOErrorEvent)
	{
		retrytimer.stop();
		FlashNetworkClient.finalize();
		updatecallback("Finished.");
	}
	
	public function progress(e : flash.events.Event)
	{
		retrytimer.stop();
		retrytimer.start();
		status = status_transferring;
	}

}
